const Service = require('egg').Service;
const BigNumber = require('bignumber.js');
const Web3 = require('web3');
const HDWalletProvider = require('truffle-hdwallet-provider');
const mnemonic = "winner weird snack cry today penalty isolate joy secret turn jealous wagon"
const url = "https://rinkeby.infura.io/v3/ef8cd40931114dabb4032fc0314a4d55";
const web3 = new Web3(new HDWalletProvider(mnemonic, url));
// 前段订单列表
const listRule = {
    userAddress: {type: 'string'}
};

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

// 前段买涨买跌统计
const isBuyCountRule = {
    openTime: {type: 'string'},
    closeTime: {type: 'string'},
}

class ActionCreateService extends Service {
    async create() {
       
        const ctx = this.ctx;
        // ctx.request.body.amount =  web3.utils.fromWei(amount, 'ether');//amount;
        let left = ctx.request.body.actionSelector.split("(");
        let right = left[1].split(")");
        let actionSelectorArr = right[0].split(",");
        actionSelectorArr = ['string', actionSelectorArr[0], actionSelectorArr[1], actionSelectorArr[2], actionSelectorArr[3]];
        
        //actionSelectorArr = actionSelectorArr.splice(0,4)
        
        let payloadObj = web3.eth.abi.decodeParameters(actionSelectorArr, ctx.request.body.payload);
        // uuid , actionSelect , amount, isBUy
        let uuid = payloadObj[1];
        let actionSelector = payloadObj[0];
        // 判断是否与传过来的不一致
        if(ctx.request.body.actionSelector != actionSelector) {
            return {'status_code':422, 'msg': 'actionSelector 数据类型不一致！'};
        }
        let amount = payloadObj[2];
        let isBuy = payloadObj[3];

        let sign = ctx.request.body.sign;
        let userAddress = ctx.request.body.userAddress;
        let userTimeStamp = ctx.request.body.userTimeStamp;
        let encodeParameters = ctx.request.body.payload; // 
        let srvTimestamp = Date.now();

        const sign_userAddress = await web3.eth.personal.ecRecover(ctx.request.body.payload, sign);
        
        const query_acount_userAddressIsset = {
            where: {
                userAddress: userAddress
            }
        };
        const account_userAddress_isset = await ctx.model.Account.findAll(query_acount_userAddressIsset);
        
        // validate account/userAddress isset 
        if(account_userAddress_isset.length == 0) {
            return {'status_code':422, 'msg': '用户不存在，请不要非法操作！'};
        };
       
        // validate userAddress 
        if(sign_userAddress != userAddress.toLowerCase()) {
            return  {'status_code':422, 'msg': '用户不一致！'};
        }
        
        // validate uuid required
        const query_actionUuidRequired = {
            where: {
                uuid: uuid
            }
        };
        const uuidRequired = await ctx.model.Action.findAll(query_actionUuidRequired);
        if(uuidRequired.length != 0) {
            return {'status_code':422, 'msg': '随机数已存在'};
            
        }
        // 获取account  id 插入 action/account_id
        let accountRow = await ctx.model.Account.findOne({
            where: {
                userAddress: ctx.request.body.userAddress
            }
        });
        
        // ------------------------------其次就是获取合约用户的balance 和本地对比------------------------------
        // const contractBalance = "9899958.9999999999999997"; // 合约的

        // const balanceZero = new BigNumber(accountRow.balance).minus(new BigNumber(accountRow.freezeBalance)).minus(new BigNumber(contractBalance))>0;

        // if(balanceZero) {
        //     ctx.status = 422;
        //     ctx.body =  {'status_code':422, 'msg': "金额有问题，请联系我们！"};
        //     return; 
        // }

        let accountId = accountRow.id;
      
        return {
            'uuid': uuid, 'actionSelector': actionSelector,
            'userTimeStamp': userTimeStamp, 'srvTimestamp': srvTimestamp, 
            'amount':amount, 'sign': sign, 'accountId': accountId, 
            'isBuy':isBuy, 'encodeParameters':encodeParameters, 'status_code': 200
        }
      
       
    }

    async cashCreate() {
        const ctx = this.ctx;
        
        // uuid , actionSelect , amount, isBUy
        

        // let uuid = "0x20852547a7e495617711b7d03fc8f3bd5e30371ee6cc10e7ce87f6faf874f711";
        // let actionSelector = 123;
        // let amount = "1000000000000000001";
        // let isBuy = 1;
        // ctx.request.body.amount =  web3.utils.fromWei(amount, 'ether');//amount;
        let left = ctx.request.body.actionSelector.split("(");
        let right = left[1].split(")");

        let actionSelectorArr = right[0].split(",");
        actionSelectorArr = ['string', actionSelectorArr[0], actionSelectorArr[1]];
        
        let payloadObj = web3.eth.abi.decodeParameters(actionSelectorArr, ctx.request.body.payload);

        let uuid = payloadObj[1];
        let actionSelector = payloadObj[0];
        // 判断是否与传过来的不一致
        if(ctx.request.body.actionSelector != actionSelector) {
            return {'status_code':422, 'msg': 'actionSelector 数据类型不一致！'};
        }
        let amount = payloadObj[2];
        let isBuy = payloadObj[3];

        let sign = ctx.request.body.sign;
        let userAddress = ctx.request.body.userAddress;
        let userTimeStamp = ctx.request.body.userTimeStamp;
        let encodeParameters = ctx.request.body.payload; // 


        let srvTimestamp = Date.now();
        const sign_userAddress = await web3.eth.personal.ecRecover(ctx.request.body.payload, sign);
        
        const query_acount_userAddressIsset = {
            where: {
                userAddress: userAddress
            }
        };
        const account_userAddress_isset = await ctx.model.Account.findAll(query_acount_userAddressIsset);
        
        // validate account/userAddress isset 
        if(account_userAddress_isset.length == 0) {
            return {'status_code':422, 'msg': '用户不存在，请不要非法操作！'};
        };
       
        // validate userAddress 
        if(sign_userAddress != userAddress.toLowerCase()) {
            return  {'status_code':502, 'msg': '用户不一致！'};
        }
        
        // validate uuid required
        const query_actionUuidRequired = {
            where: {
                uuid: uuid
            }
        };
        const uuidRequired = await ctx.model.Action.findAll(query_actionUuidRequired);
        if(uuidRequired.length != 0) {
            return {'status_code':422, 'msg': '随机数已存在'};
            
        }
        // 获取account  id 插入 action/account_id
        let accountRow = await ctx.model.Account.findOne({
            where: {
                userAddress: ctx.request.body.userAddress
            }
        });
        // ------------------------------其次就是获取合约用户的balance 和本地对比------------------------------
        // const contractBalance = "9899958.9999999999999997"; // 合约的

        // const balanceZero = new BigNumber(accountRow.balance).minus(new BigNumber(accountRow.freezeBalance)).minus(new BigNumber(contractBalance))>0;

        // if(balanceZero) {
        //     ctx.status = 422;
        //     ctx.body =  {'status_code':422, 'msg': "金额有问题，请联系我们！"};
        //     return; 
        // }

        let accountId = accountRow.id;
       
        return {
            'uuid': uuid, 'actionSelector': actionSelector,
            'userTimeStamp': userTimeStamp, 'srvTimestamp': srvTimestamp, 
            'amount':amount, 'sign': sign, 'accountId': accountId, 
            'isBuy':isBuy, 'encodeParameters':encodeParameters, 'status_code': 200
        }
       
       
    }
    
}
module.exports = ActionCreateService;